package stark.app.function.visualai;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.app.R;
import stark.app.databinding.FragmentVisualAiFuncBinding;
import stark.common.apis.ApiManager;
import stark.common.apis.visionai.base.EmotionEditType;
import stark.common.apis.visionai.base.ImgStyleType;
import stark.common.base.IReqRetCallback;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.constant.Extra;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * Author：daizhongbin on 2023/10/11
 * Email：1027154338@qq.com
 * Desc:
 */
public class VisualAiFuncFragment extends BaseNoModelFragment<FragmentVisualAiFuncBinding> {

    private VisualAiFuncType mFuncType = VisualAiFuncType.FACE_PRETTY;
    private Uri mSelPicUri;
    private boolean hasOpenSpecialEffect = false;
    private Bitmap mSpecialEffectBmp;

    public static Bundle createArguments(VisualAiFuncType funcType) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(Extra.TYPE, funcType);
        return bundle;
    }

    @Override
    protected int onCreate() {
        return R.layout.fragment_visual_ai_func;
    }

    @Override
    protected void initView() {
        Bundle bundle = getArguments();
        if (bundle != null && bundle.containsKey(Extra.TYPE)) {
            mFuncType = (VisualAiFuncType) bundle.getSerializable(Extra.TYPE);
        }
        if (mFuncType == null) {
            mFuncType = VisualAiFuncType.FACE_PRETTY;
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mDataBinding.rvContainer.setLayoutManager(layoutManager);
        VisualAiFuncActionAdapter adapter = new VisualAiFuncActionAdapter();
        adapter.setOnItemClickListener(this);
        adapter.setNewInstance(getActionNamesByType(mFuncType));
        mDataBinding.rvContainer.setAdapter(adapter);

        //sel pic
        mDataBinding.btnSelPic.setOnClickListener(v -> {
            handleClickSelPic();
        });
        //yingxiang compare
        mDataBinding.ivImgCompare.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!hasOpenSpecialEffect) return true;
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Glide.with(mDataBinding.ivRet).load(mSelPicUri).into(mDataBinding.ivRet);
                        break;
                    case MotionEvent.ACTION_UP:
                        mDataBinding.ivRet.setImageBitmap(mSpecialEffectBmp);
                        break;
                }
                return true;
            }
        });
        //download
        mDataBinding.ivDownload.setOnClickListener(v -> {
            handleClickDownload();
        });
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        ((VisualAiFuncActionAdapter) adapter).setSelPos(position);
        switch (mFuncType) {
            case AGE_GENERATION:
                handleItemClickForAgeGeneration(position);
                break;
            case EMOTION_EDIT:
                handleItemClickForEmotionEdit(position);
                break;
            case IMG_STYLE_CONVERSION:
                handleItemClickForImgStyleConversion(position);
                break;
            default:
                handleItemClickForOthers(position);
                break;
        }
    }

    private void handleItemClickForAgeGeneration(int position) {
        if (position == 0) {
            closeSpecialEffect();
        } else if (position == 1) {
            openSpecialEffect(5);
        } else {
            openSpecialEffect(70);
        }
    }

    private void handleItemClickForEmotionEdit(int position) {
        if (position == 0) {
            closeSpecialEffect();
        } else {
            openSpecialEffect(position - 1);
        }
    }

    private void handleItemClickForImgStyleConversion(int position) {
        if (position == 0) {
            closeSpecialEffect();
        } else {
            openSpecialEffect(position - 1);
        }
    }

    private void handleItemClickForOthers(int position) {
        if (position == 0) {
            closeSpecialEffect();
        } else {
            openSpecialEffect(null);
        }
    }

    private List<String> getActionNamesByType(VisualAiFuncType funcType) {
        List<String> list = new ArrayList<>();
        list.add("关闭特效");
        switch (funcType) {
            case AGE_GENERATION:
                list.add("变年轻");
                list.add("变老");
                break;
            case EMOTION_EDIT:
                list.add("露牙笑");
                list.add("嘟嘟嘴");
                list.add("不高兴");
                list.add("闭嘴笑");
                break;
            case IMG_STYLE_CONVERSION:
                for (ImgStyleType type : ImgStyleType.values()) {
                    list.add(type.getName());
                }
                break;
            default:
                list.add("打开特效");
                break;
        }
        return list;
    }

    private void handleClickSelPic() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc("获取照片需要存储权限，请授予")
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        PhotoSelectorBuilder.builder(getActivity())
                                .mode(PhotoConfig.Mode.PHOTO)
                                .maxCount(1)
                                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                                    @Override
                                    public void onResult(List<SelectMediaEntity> data) {
                                        if (data == null || data.size() == 0) {
                                            return;
                                        }
                                        mSelPicUri = Uri.parse(data.get(0).getUri());
                                        Glide.with(mDataBinding.ivRet).load(mSelPicUri).into(mDataBinding.ivRet);
                                        hasOpenSpecialEffect = false;
                                    }
                                });
                    }
                })
                .request();
    }

    private void handleClickDownload() {
        if (!hasOpenSpecialEffect || mSpecialEffectBmp == null) return;
        showDialog(getString(com.stark.common.res.R.string.saving));
        RxUtil.create(new RxUtil.Callback<File>() {
            @Override
            public void doBackground(ObservableEmitter<File> emitter) {
                emitter.onNext(ImageUtils.save2Album(mSpecialEffectBmp, Bitmap.CompressFormat.JPEG));
            }

            @Override
            public void accept(File file) {
                dismissDialog();
                ToastUtils.showShort(file == null ? "保存失败" : "已保存");
            }
        });
    }

    /**
     * 关闭特效
     */
    private void closeSpecialEffect() {
        if (mSelPicUri != null) {
            Glide.with(mDataBinding.ivRet).load(mSelPicUri).into(mDataBinding.ivRet);
        }
        hasOpenSpecialEffect = false;
    }

    /**
     * 打开特效
     */
    private void openSpecialEffect(@Nullable Integer value) {
        if (!checkSelPic()) return;
        IReqRetCallback<Bitmap> callback = new IReqRetCallback<Bitmap>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable Bitmap result) {
                dismissDialog();
                ToastUtils.showShort(msg);
                if (result != null) {
                    mSpecialEffectBmp = result;
                    mDataBinding.ivRet.setImageBitmap(result);
                    hasOpenSpecialEffect = true;
                }
            }
        };
        showDialog("处理中，请不要退出该界面");
        switch (mFuncType) {
            case AGE_GENERATION:
                ApiManager.visionAiApi().ageGeneration(this, mSelPicUri, value, callback);
                break;
            case F3DCARTOON:
                ApiManager.visionAiApi().f3DGameCartoon(this, mSelPicUri, callback);
                break;
            case FACE_PRETTY:
                ApiManager.visionAiApi().facePretty(this, mSelPicUri, callback);
                break;
            case EYE_CLOSE2OPEN:
                ApiManager.visionAiApi().eyeClose2Open(this, mSelPicUri, callback);
                break;
            case REPAIR_OLD_PHOTO:
                ApiManager.visionAiApi().repairOldPhoto(this, mSelPicUri, callback);
                break;
            case EMOTION_EDIT:
                ApiManager.visionAiApi().emotionEdit(this, mSelPicUri, EmotionEditType.get(value), callback);
                break;
            case IMG_STYLE_CONVERSION:
                ApiManager.visionAiApi().imgStyleConversion(this, mSelPicUri, ImgStyleType.get(value), callback);
                break;
            case ENHANCE_PHOTO:
                ApiManager.visionAiApi().enhancePhoto(this, mSelPicUri, callback);
                break;
        }
    }

    private boolean checkSelPic() {
        if (mSelPicUri == null) {
            ToastUtils.showShort("请先选择照片");
            return false;
        }
        return true;
    }
}
